package com.dlc.beijingrfid.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import com.bumptech.glide.Glide;
import com.dlc.commonlibrary.dialog.UpdateDialog;
import com.dlc.commonlibrary.utils.DataCleanManager;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.utils.glide.GlideUtil;
import com.dlc.commonlibrary.utils.glide.transform.BlurTransform;
import com.dlc.commonlibrary.widget.MyItemView;
import com.dlc.commonlibrary.widget.TitleBar;
import com.dlc.beijingrfid.R;
import com.dlc.beijingrfid.activity.AboutWeActivity;
import com.dlc.beijingrfid.activity.ForgetPasswordActivity;
import com.dlc.beijingrfid.activity.MessageActivity;
import com.dlc.beijingrfid.activity.OpinionFeedbackActivity;
import com.dlc.beijingrfid.activity.SettingActivity;
import com.dlc.beijingrfid.base.BaseFragment;
import com.dlc.beijingrfid.helper.UpdateAppHttpUtil;
import com.dlc.beijingrfid.helper.UserHelper;
import com.dlc.beijingrfid.net.NetConstants;
import com.dlc.beijingrfid.net.bean.NewApkBean;
import com.dlc.beijingrfid.net.bean.NoticeNoreadsBean;
import com.dlc.beijingrfid.net.exception.ErrorMsgException;
import com.dlc.beijingrfid.net.protocol.UserProto;
import com.dlc.beijingrfid.net.protocol.base.HttpProtocol;
import com.google.gson.Gson;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by John on 2017/7/18.
 */

public class MineFragment extends BaseFragment implements View.OnClickListener {
   /* @BindView(R.id.my_bg)
    LinearLayout my_bg;*/
    @BindView(R.id.item_feedback)
   MyItemView item_feedback;
    @BindView(R.id.alter_psd)
    MyItemView alter_psd;
    @BindView(R.id.titleBar)
    TitleBar titleBar;
    @BindView(R.id.about)
    MyItemView about;
    @BindView(R.id.version_update)
    MyItemView version_update;
    @BindView(R.id.clear_cache)
    MyItemView clear_cache;
    @BindView(R.id.head_setting)
    ImageView head_setting;
    @BindView(R.id.nickname_tv)
    TextView nickname_tv;
    @BindView(R.id.phone_tv)
    TextView phone_tv;
    @BindView(R.id.head_bg)
    ImageView head_bg;
    String nickname;
    String avatar;
    private UpdateDialog updateDialog;


    @Override
    public void onCreateView() {
      /*  Drawable drawable = ArithmeticUtil.BoxBlurFilter(BitmapFactory.decodeResource(getResources(), R.mipmap.temporary_bg));
        if (drawable != null) {
            my_bg.setBackground(drawable);
        }*/
        setClickListener();
        Glide.with(this)
                .load(UserHelper.get().getAvatar())
                .placeholder(R.mipmap.ic_default_avatar)
                .dontAnimate()
                .transform(new BlurTransform(getActivity()))
                .into(head_bg);
        if(!TextUtils.isEmpty(UserHelper.get().getAvatar())){
            Log.d("头像url--->",UserHelper.get().getAvatar());
            GlideUtil.loadCircleImg(getActivity(), UserHelper.get().getAvatar(),
                    head_setting);


        }else {
            head_setting.setImageDrawable(getResources().getDrawable(R.mipmap.ic_launcher_round));
        }
        if(!TextUtils.isEmpty(UserHelper.get().getNickname())){
            nickname= UserHelper.get().getNickname();
            nickname_tv.setText(UserHelper.get().getNickname());
        }else {
            nickname= "-----";
            nickname_tv.setText(nickname);
        }
        phone_tv.setText(UserHelper.get().getAccount());

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my;
    }

    private void setClickListener() {
        titleBar.rightImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), MessageActivity.class));
            }
        });
        head_setting.setOnClickListener(this);
        item_feedback.setOnClickListener(this);
        alter_psd.setOnClickListener(this);
        about.setOnClickListener(this);
        version_update.setOnClickListener(this);
        clear_cache.setOnClickListener(this);
        try {
            clear_cache.txtRight.setText(DataCleanManager.getTotalCacheSize(getActivity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        getAppVersionName(getActivity());
    }
    @Override
    public void onStart() {
        super.onStart();
        notice_noreads();
    }

    public void notice_noreads() {
        UserProto.get().notice_noreads(new HttpProtocol.Callback<NoticeNoreadsBean>() {
            @Override
            public void onSuccess(NoticeNoreadsBean noticeNoreadsBean) {
                int num = Integer.parseInt(noticeNoreadsBean.data.noreads);
                if (num > 0) {
                    titleBar.setRightImageBackground(R.mipmap.ling);
                }else {
                    titleBar.setRightImageBackground(R.mipmap.ic_news);
                }
            }

            @Override
            public void onFailed(int code, ErrorMsgException e) {
                if (code == 0) {
                    showOneToast(getString(R.string.net_error));
                }else {
                    showOneToast(e.getMessage());
                }
            }
        });
    }
    /**
     * 返回当前程序版本名
     */
    public  void  getAppVersionName(Context context) {
        int versioncode = 0;
        String version = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versioncode = pi.versionCode;
            version = pi.versionName;
            if (!TextUtils.isEmpty(version)){
                version = "v"+version;
                version_update.txtRight.setText(version);
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.head_setting:
                Intent intent=new Intent(getActivity(), SettingActivity.class);
                intent.putExtra("avatar",UserHelper.get().getAvatar());
                intent.putExtra("nickname",nickname);
                Log.d("头像保存的url---->",UserHelper.get().getAvatar());
                startActivityForResult(intent,0);
                break;
            case R.id.item_feedback:
                startActivity(new Intent(getActivity(), OpinionFeedbackActivity.class));
                break;
            case R.id.alter_psd:
                Intent intent1 =new Intent(getActivity(), ForgetPasswordActivity.class);
                intent1.putExtra("tab",1);
                startActivity(intent1);
                break;
            case R.id.about:
                startActivity(new Intent(getActivity(), AboutWeActivity.class));
                break;
            case R.id.version_update:
                Toast.makeText(getActivity(),"已是最新版",Toast.LENGTH_SHORT).show();
                update();
                break;
            case R.id.clear_cache:
                Toast.makeText(getActivity(),"已清理完畢",Toast.LENGTH_SHORT).show();
                try {
                    DataCleanManager.clearAllCache(getActivity());
                    clear_cache.txtRight.setText(DataCleanManager.getTotalCacheSize(getActivity()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;

        }

    }

    private void update() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        Map<String, String> params = new HashMap<>();
        // params.put("token", UserHelper.get().getToken());

        StringBuilder sb = new StringBuilder(NetConstants.BASE_URL);
        sb.append("version")
            .append("?")
            .append("userid=")
            .append(UserHelper.get().getId())
            .append("&timestamp=")
            .append(UserHelper.get().getTimestamp())
            .append("&sign=")
            .append(UserHelper.get().getSign());

        new UpdateAppManager.Builder()
            //必须设置，当前Activity
            .setActivity(getActivity())
            //必须设置，实现httpManager接口的对象
            .setHttpManager(new UpdateAppHttpUtil())
            //必须设置，更新地址
            .setUpdateUrl(sb.toString())
            //以下设置，都是可选
            //设置请求方式，默认get
            .setPost(true)
            //添加自定义参数，默认version=1.0.0（app的versionName）；apkKey=唯一表示（在AndroidManifest.xml配置）
            .setParams(params)
            //设置点击升级后，消失对话框，默认点击升级后，对话框显示下载进度
            .hideDialogOnDownloading()
            //设置头部，不设置显示默认的图片，设置图片后自动识别主色调，然后为按钮，进度条设置颜色
            .setTargetPath(path)
            //是否忽略版本
            //.showIgnoreVersion()
            .build()
            //检测是否有新版本
            .checkNewApp(new UpdateCallback() {
                /**
                 * 解析json,自定义协议
                 *
                 * @param json 服务器返回的json
                 * @return UpdateAppBean
                 */
                @Override
                protected UpdateAppBean parseJson(String json) {
                    LogPlus.e(json);
                    UpdateAppBean updateAppBean = new UpdateAppBean();
                    try {
                        Gson gson = new Gson();
                        NewApkBean newApkBean = gson.fromJson(json, NewApkBean.class);
                        if (newApkBean.code == 1) {
                            if (newApkBean.data.hotel_ver.compareTo(getLocalVersionName()) > 0) {
                                updateAppBean
                                    //（必须）是否更新Yes,No
                                    .setUpdate("Yes")
                                    //（必须）新版本号，
                                    .setNewVersion(newApkBean.data.hotel_ver)
                                    //（必须）更新内容
                                    .setUpdateLog("更新")
                                    //（必须）下载地址
                                    .setApkFileUrl(newApkBean.data.hotel_url)

                                    //是否强制更新，可以不设置
                                    .setConstraint(false);
                            } else {
                                showOneToast("没有新版本");
                            }
                        } else {
                            showOneToast(newApkBean.msg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return updateAppBean;
                }

                /**
                 * 网络请求之前
                 */
                @Override
                public void onBefore() {
                   // showWaitingDialog("请稍后...", false);
                }

                /**
                 * 网路请求之后
                 */
                @Override
                public void onAfter() {
                    dismissWaitingDialog();
                }

                @Override
                protected void hasNewApp(UpdateAppBean updateApp, UpdateAppManager updateAppManager) {
                    updateDialog = new UpdateDialog(getContext(), updateApp, updateAppManager);
                    updateDialog.show();
                }
            });
    }
    public String getLocalVersionName() {
        String versionName = "";
        try {
            PackageInfo packageInfo = getActivity().getApplicationContext().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
            versionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==1&&data!=null){
            String avatar= data.getExtras().getString("avatar");
            String nickName=data.getExtras().getString("nickname");
            if(!TextUtils.isEmpty(avatar)){
                Log.d("头像上传成功回调url---->",""+avatar);
                GlideUtil.loadCircleImg(getActivity(), data.getStringExtra("avatar"),
                        head_setting);
                Glide.with(this)
                        .load(data.getStringExtra("avatar"))
                        .placeholder(R.mipmap.ic_default_avatar)
                        .dontAnimate()
                        .transform(new BlurTransform(getActivity()))
                        .into(head_bg);
            }
            if(!TextUtils.isEmpty(nickName)){
                nickname_tv.setText(nickName);
            }
        }
    }
}

